package com.lemon.smartsafetynew.ui.activity.notice;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.common.FileUtil;
import com.lemon.smartsafetynew.entity.event.common.ViewEvent;
import com.lemon.smartsafetynew.entity.notice.NoticeInfoListVo;
import com.lemon.smartsafetynew.entity.notice.NoticeItemVo;
import com.lemon.smartsafetynew.net.services.NoticeServices;
import com.lemon.smartsafetynew.ui.adapter.notice.NoticeInfoLIstAdapter;
import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.common.MyIntent;
import com.lemon.smartsafetynew.util.common.UrlFormatUtils;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.user.AccountUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import okhttp3.Call;

/**
 * Created by Andrew on 2017/11/3.
 */

public class NoticeDetailActivity extends SwipeBackActivity {

    private static NoticeItemVo noticeItemVo;

    @Bind(R.id.notice_title_tv)
    TextView noticeTitleTv;
    @Bind(R.id.notice_timestamp_tv)
    TextView noticeTimestampTv;
    @Bind(R.id.notice_name_tv)
    TextView noticeNameTv;
    @Bind(R.id.notice_content_tv)
    TextView noticeContentTv;
    @Bind(R.id.listview)
    ListView listview;
    @Bind(R.id.tv_fujian)
    TextView tvFujian;

    private List<NoticeInfoListVo> datas;
    private NoticeInfoLIstAdapter adapter;

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();

        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            if (bundle.containsKey(KeyConstants.KEY_NOTICE_ITEM_VO)) {
                noticeItemVo = (NoticeItemVo) bundle.getSerializable(KeyConstants.KEY_NOTICE_ITEM_VO);
            }
        }
    }

    @Override
    protected void initListener() {
        super.initListener();
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                getFile(datas.get(i).getUrl(), datas.get(i).getName());
            }
        });
    }

    @Override
    protected void initTitle() {
        this.setBarTitle("公  告");
    }

    @Override
    protected void callFinish() {
        AppService.getBus().post(new ViewEvent(NoticeDetailActivity.class.getName()));
        AppManager.getAppManager().finishActivity(NoticeDetailActivity.this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_notice_detail_new;
    }

    @Override
    protected void initViews() {
        super.initViews();

        getDetailData();
    }

    private void getDetailData() {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("user_id", AccountUtil.getUserID());
        params.put("notice_id", noticeItemVo.getId());
        NoticeServices.init().readNoticeDetail(params);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainThread(HttpCallbackEvent event) {

        if (KeyConstants.URL_READ_NOTICE_DETAIL.equals(event.getTag())) {                           //
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.show();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                mHUDUtil.hidden();
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    if (event.getObj() instanceof NoticeItemVo) {
                        NoticeItemVo noticeItemVo = (NoticeItemVo) event.getObj();
                        initNotice(noticeItemVo);
                    }

                } else {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                        }
                    });
                }
            }
        }
    }

    private void initNotice(NoticeItemVo data) {
        noticeTitleTv.setFocusable(true);
        noticeTitleTv.setFocusableInTouchMode(true);
        noticeTitleTv.requestFocus();
        noticeTitleTv.setText(CommonUtil.avoidNullString(data.getTitle()));
        noticeTimestampTv.setText(CommonUtil.timeToStr(data.getRecord_date()));
        noticeNameTv.setText(CommonUtil.avoidNullString(data.getRecorder_name()));
        noticeContentTv.setText(CommonUtil.avoidNullString(data.getContent()));
        if (data.getFiles() != null && !"".equals(data.getFiles())) {
            tvFujian.setVisibility(View.VISIBLE);
            listview.setVisibility(View.VISIBLE);
            datas = new ArrayList<>();
            String[] files = data.getFiles().split(",");
            List<String> fileNameList = new ArrayList<>();

            if(data.getFile_names() != null) {

                fileNameList = Arrays.asList(data.getFile_names().split(","));

                if(files.length != fileNameList.size()) {
                    fileNameList.clear();
                    for(String fileUrl: files) {
                        fileNameList.add(fileUrl.substring((fileUrl.lastIndexOf("/") + 1), fileUrl.length()));
                    }
                }

            } else {
                fileNameList.clear();
                for(String fileUrl: files) {
                    fileNameList.add(fileUrl.substring((fileUrl.lastIndexOf("/") + 1), fileUrl.length()));
                }
            }

            for (int i = 0; i < files.length; i++) {
                NoticeInfoListVo listVo = new NoticeInfoListVo();
                listVo.setName(fileNameList.get(i));
                listVo.setUrl(UrlFormatUtils.formatFiles(files[i]));
                datas.add(listVo);
            }
            adapter = new NoticeInfoLIstAdapter(datas, this);
            listview.setAdapter(adapter);
        } else {
            tvFujian.setVisibility(View.GONE);
            listview.setVisibility(View.GONE);
        }
    }

    private void getFile(String fileUrl, final String fileName) {
        mHUDUtil.showHUD();
        OkHttpUtils
                .get()
                .url(fileUrl)
                .build()
                .execute(new FileCallBack(FileUtil.getAppDocNoticeDir(NoticeDetailActivity.this), fileName) {
                    @Override
                    public void onError(Call call, Exception e) {
                        mHUDUtil.showErrorTip("获取文件失败。");
                    }

                    @Override
                    public void onResponse(File response) {
                        mHUDUtil.hidden();
                        Intent intent = null;
                        if (fileName.endsWith(".xlsx") || fileName.endsWith(".xls")
                                || fileName.endsWith(".XLSX") || fileName.endsWith(".XLS")){
                            intent = MyIntent.getExcelFileIntent(response.getPath());
                        } else if(fileName.endsWith(".txt") || fileName.endsWith(".TXT")){
                            intent = MyIntent.getTextFileIntent(response.getPath(),false);
                        } else if(fileName.endsWith(".doc") || fileName.endsWith(".docx")
                                || fileName.endsWith(".DOC") || fileName.endsWith(".DOCX")){
                            intent = MyIntent.getWordFileIntent(response.getPath());
                        } else if(fileName.endsWith(".ppt") || fileName.endsWith(".PPT")
                                || fileName.endsWith(".pptx") || fileName.endsWith(".PPTX") ){
                            intent = MyIntent.getPptFileIntent(response.getPath());
                        } else if(fileName.endsWith(".pdf") || fileName.endsWith(".PDF")){
                            intent = MyIntent.getPdfFileIntent(response.getPath());
                        } else if(fileName.endsWith(".png") || fileName.endsWith(".PNG")
                                || fileName.endsWith(".jpg") || fileName.endsWith(".JPG")
                                || fileName.endsWith(".jpeg") || fileName.endsWith(".JPEG")){
                            intent = MyIntent.getImageFileIntent(response.getPath());
                        } else if(fileName.endsWith(".mp4") || fileName.endsWith(".MP4")){
                            intent = MyIntent.getVideoFileIntent(response.getPath());
                        } else if(fileName.endsWith(".wma") || fileName.endsWith(".wav") || fileName.endsWith(".mp3") ){
                            intent = MyIntent.getAudioFileIntent(response.getPath());
                        } else {
                            intent = null;
                        }

                        try {
                            if(intent != null) {
                                startActivity(intent);
                            } else {
                                mHUDUtil.showErrorTip("未能识别此类文件！");
                            }
                        } catch (Exception e) {
                           runOnUiThread(new Runnable() {
                               @Override
                               public void run() {
                                   mHUDUtil.showErrorTip("没有相应工具打开此类文件，请下载相关App查看此类文件！");
                               }
                           });
                        }
                    }

                    @Override
                    public void inProgress(float progress, long total) {

                    }
                });
    }

}
